package org.example.communication_room.service.impl;

import org.example.communication_room.Controller.UserController;
import org.example.communication_room.dao.User;
import org.example.communication_room.repository.UserRepository;
import org.example.communication_room.service.interfaces.UserService;
import org.example.communication_room.utils.JwtUtil;
import org.example.communication_room.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    public User register(String username, String password) {
        if (!UserUtils.validateUsername(username) || !UserUtils.validatePassword(password)) {
            throw new IllegalArgumentException("非法的用户名或密码");
        }
        if (userRepository.existsByUsername(username)) {
            throw new IllegalArgumentException("用户名已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setUserId(UserUtils.generateUniqueId());

        return userRepository.save(user);
    }

    //    登陆功能
    public Map<String, String> login(String username, String password) {
        if (!UserUtils.validateUsername(username) || !UserUtils.validatePassword(password)) {
            throw new IllegalArgumentException("非法的用户名或密码");
        }
        User user = userRepository.findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getUserId());
            String accessToken = JwtUtil.genAccessToken(claims);
            String refreshToken = JwtUtil.genRefreshToken(claims);
            Map<String, String> tokens = new HashMap<>();
            tokens.put("accessToken", accessToken);
            tokens.put("refreshToken", refreshToken);
            tokens.put("userId", String.valueOf(user.getUserId()));
            return tokens;
        }
        return null;
    }

    //    刷新Token
    public String refreshAccessToken(String refreshToken) {
        try {
            Map<String, Object> claims = JwtUtil.parseToken(refreshToken);
            if (claims != null) {
                claims.put("userId", claims.get("userId"));
                return JwtUtil.genAccessToken(claims);
            }
        } catch (Exception e) {
            logger.error(String.valueOf(e));
        }
        return null;
    }

    //    更新用户状态
    public void updateUserOnlineStatus(String username, boolean isOnline) {
        User user = userRepository.findByUsername(username);
        if (user != null) {
            user.setOnline(isOnline);
            userRepository.save(user);
        }
    }
    // 根据用户名寻找用户
    public User findUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    public User findUserById(String userId) {
        return userRepository.findById(Long.parseLong(userId)).orElse(null);
    }

    //    用户下线
    public void logout(String userId) {
//        获取用户信息
        User user = findUserById(userId);
        if (user != null) {
            updateUserOnlineStatus(user.getUsername(), false);  // 设置用户离线
        }
    }
}